package com.huawei.cloudapp.utils;

import static com.huawei.cloudapp.utils.CasConstantsUtil.EMPTY_STRING;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.os.SystemClock;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.huawei.cloudapp.BuildConfig;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class CasCommonUtils {

    /**
     * 判断32位uuid
     */
    private static final Pattern PATTERN_UUID = Pattern.compile("[a-f0-9]{32}");

    /**
     * phone名 校验规则
     */
    private static final Pattern NAME_PATTERN = Pattern.compile("^[-_a-zA-Z0-9\u4e00-\u9fa5]{1,60}$");
    private static final long CLICK_INTERVAL = 1000;
    private static long lastClickTime = 0;
    private static long[] mHits;
    private static Gson gson = new Gson();
    private static Type typeMap = new TypeToken<Map<String, Object>>(){}.getType();
    private static Type typeList = new TypeToken<List<Map<String, Object>>>(){}.getType();
    private static String encryptPass = "";
    private static String encryptIV = "";

    public static boolean isFastClick() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastClickTime <= CLICK_INTERVAL) {
            return true;
        }
        lastClickTime = currentTime;
        return false;
    }

    public static Map<String, Object> parseJsonMessage(String message) {
        if (message == null || message.length() == 0) {
            return new HashMap<>();
        }
        try {
            return gson.fromJson(message, typeMap);
        } catch (JsonSyntaxException e) {
            return new HashMap<>();
        }
    }

    public static List<Map<String, String>> parseJsonListMessage(String message) {
        if (message == null || message.length() == 0) {
            return new ArrayList<>();
        }
        try {
            return gson.fromJson(message, typeList);
        } catch (JsonSyntaxException e) {
            return new ArrayList<>();
        }
    }

    public static boolean onJumpToDebugView() {
        if (mHits == null) {
            mHits = new long[5];
        }
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();
        if (SystemClock.uptimeMillis() - mHits[0] <= 1000) {
            mHits = null;
            return true;
        }
        return false;
    }

    public static boolean isSupportH265() {
        MediaCodecList mediaCodecList = new MediaCodecList(MediaCodecList.ALL_CODECS);
        String mimeType = "video/hevc";
        return mediaCodecList.findDecoderForFormat(
                MediaFormat.createVideoFormat(mimeType, 1920, 1080)) != null;
    }

    public static boolean isDirectMode() {
        return BuildConfig.IS_DIRECT_MODE;
    }

    public static String getManagementUrl() {
        return CasConstantsUtil.MANAGEMENT_PROD_ENV_URL;
    }

    public static String getEncryptPass() {
        return encryptPass;
    }

    public static void setEncryptPass(String pass) {
        CasCommonUtils.encryptPass = pass;
    }

    public static String getEncryptIV() {
        return encryptIV;
    }

    public static void setEncryptIV(String encryptIV) {
        CasCommonUtils.encryptIV = encryptIV;
    }

    public static int dip2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public static boolean isValidUUID(String uuid) {
        return !isStringEmpty(uuid) && PATTERN_UUID.matcher(uuid).matches();
    }

    public static boolean isValidPhoneName(String phoneName) {
        return !isStringEmpty(phoneName) && NAME_PATTERN.matcher(phoneName).matches();
    }

    public static boolean isStringEmpty(String str) {
        return str == null || str.length() == 0;
    }

    public static String getApkVersion(Context context) {
        if (context == null) {
            return EMPTY_STRING;
        }
        try {
            // getPackageName()是当前类的包名，0代表是获取版本信息
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return EMPTY_STRING;
    }

    public static Bitmap makeBitmapSquare(Bitmap oldBitmap, int newWidth) {
        Bitmap newBitmap;
        if (oldBitmap.getWidth() > oldBitmap.getHeight()) {
            newBitmap = Bitmap.createBitmap(oldBitmap, oldBitmap.getWidth() / 2 - oldBitmap.getHeight() / 2, 0, oldBitmap.getHeight(), oldBitmap.getHeight());
        } else {
            newBitmap = Bitmap.createBitmap(oldBitmap, 0, oldBitmap.getHeight() / 2 - oldBitmap.getWidth() / 2, oldBitmap.getWidth(), oldBitmap.getWidth());
        }
        int width = newBitmap.getWidth();
        float scaleWidth = ((float) newWidth) / width;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleWidth);
        newBitmap = Bitmap.createBitmap(newBitmap, 0, 0, width, width, matrix, true);
        return newBitmap;
    }
}
